package com.ykefu.assign.netty.netty.http;

import com.alibaba.fastjson.JSONObject;
import com.ykefu.assign.config.ThreadPoolExecutorConfig;
import com.ykefu.assign.constant.MimeType;
import com.ykefu.assign.domain.HttpServerResponseBody;
import com.ykefu.assign.domain.req.PushContentBody;
import com.ykefu.assign.netty.netty.websocket.HandlerMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;

/**
 * @author likai
 * @date 2020/4/17 10:20
 * @email likai@7moor..com
 * @desc
 */
public class HttpController {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpController.class);




    public static void handler(ChannelHandlerContext ctx, FullHttpRequest req){
        String requestBody = req.content().toString(Charset.forName("UTF-8"));
        LOGGER.info("接受到的body:{}",requestBody);
        PushContentBody pushContentBody = JSONObject.parseObject(requestBody, PushContentBody.class);
        HttpServerResponseBody<Object> responseBody = HttpServerResponseBody.buildSuccess();
        String responseBodyStr= JSONObject.toJSONString(responseBody);
        ByteBuf content = Unpooled.copiedBuffer(responseBodyStr,Charset.forName("UTF-8"));
        FullHttpResponse res = new DefaultFullHttpResponse(req.protocolVersion(), OK, content);
        res.headers().set(CONTENT_TYPE, MimeType.application_json);
        HttpUtil.setContentLength(res, content.readableBytes());
        ResponseWriteUtil.sendHttpResponse(ctx, req, res);
        //发送消息
        ThreadPoolExecutorConfig.EXECUTORS.execute(()->{
            LOGGER.info("推送消息：{}",requestBody);
            HandlerMessage.getInstance().sendToUser(pushContentBody.getConnectUuid(),pushContentBody.getContent());
        });
    }
}
